/**
 * Date:2021年3月15日 上午10:24:47
 * Copyright (c) 2021, www.bwbroad.com All Rights Reserved
 */

package com.app.rabbit;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.MessageProperties;

/**
 * 
 * Description: 参考 https://blog.csdn.net/qq_36357242/article/details/107686056
 * <br/>
 * Date:2021年3月31日 下午3:16:31 <br/>
 * 
 * @author xuejianxin
 */
@Component
public class TTLProducer {

	private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TTLProducer.class);

	@Autowired
	private RabbitTemplate rabbitTemplate;

	// 死信交换机
	@Bean
	public DirectExchange deadExchange() {
		return new DirectExchange("dead-exchange");
	}

	// 死信队列
	@Bean
	public Queue deadQueue() {
		return new Queue("deadQueue");
	}

	// 延时10s的队列
	@Bean
	public Queue delay10Queue() {
		Map<String, Object> arguments = new HashMap<>();
		// 设置延时
		arguments.put("x-message-ttl", 10 * 1000);
		// 指定消息死亡后发送到 dead-exchange的交换机去
		arguments.put("x-dead-letter-exchange", "dead-exchange");
		arguments.put("x-dead-letter-routing-key", "delay10");

		return new Queue("delay10Queue", true, false, false, arguments);
	}

	// 将死信交换机绑定到死信队列
	@Bean
	public Binding directBindingDead(DirectExchange deadExchange, Queue deadQueue) {
		return BindingBuilder.bind(deadQueue).to(deadExchange).with("delay10");
	}

	// 创建消息发送者
	public void sendToDelay10Queue(String msg) {
		//BasicProperties mp=new BasicProperties();
		//Message msgObj=new Message(new String(msg), messageProperties);
		
//		rabbitTemplate.convertAndSend(RabbitmqConfig.DEMO_EXCHANGE, RabbitmqConfig.DEMO_ROUTEKEY,message, new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                //设置消息的过期时间，是以毫秒为单位的
//                message.getMessageProperties().setExpiration(ttl);
//                return message;
//            }
//        });

		
		
		
		
		String context = "sendToDelay10Queue发送的消息:" + msg;
		this.rabbitTemplate.convertAndSend("delay10Queue", context);
		log.info("sendToDelay10Queue  routeKey={},msg={} ", "delay10Queue", msg);
	}

}
